import pickle, base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """购物车合并工具方法：将cookie购物车合并到redis购物车"""

    # 读取用户浏览器中cookie购物车数据
    cart_str = request.COOKIES.get('cart')

    if not cart_str:
        # 如果没有cookie购物车数据不存在，就不需要合并，直接相应
        return response

    cart_str_bytes = cart_str.encode()
    cart_dict_bytes = base64.b64decode(cart_str_bytes)
    cookie_cart_dict = pickle.loads(cart_dict_bytes)



    # 读取redis中的购物车数据
    redis_coon = get_redis_connection('cart')

    redis_cart_dict = redis_coon.hgetall('cart_%s' % user.id)
    redis_selected_dict = redis_coon.smembers('selected_%s' % user.id)

    # 合并cookie到redis
    for sku_id, cookie_dict in cookie_cart_dict.items():
        # 将cookie_dict 合并到redis_cart_dict
        redis_cart_dict[sku_id] = cookie_dict['count']

        # 将sku_id合并到redis_selected_dict
        if cookie_dict['selected']:
            redis_selected_dict.add(sku_id)

    # 需要将合并的数据同步到redis
    redis_coon.hmset('cart_%s' % user.id, redis_cart_dict)
    redis_coon.sadd('selected_%s' % user.id, *redis_selected_dict)

    # 合并结束后，需要清空cookie购物车
    response.delete_cookie('cart')

    # 相应数据
    return response
